package manage

import (
	"github.com/gofiber/fiber/v2"
	logger "github.com/sirupsen/logrus"

	"publish-manage/internal/model"
	"publish-manage/internal/service"
	"publish-manage/pkg/constant"
	"publish-manage/pkg/domain"
	"publish-manage/pkg/server"
)

var PackageVersionController = new(packageVersionController)

type packageVersionController struct{}

//GetInstance GET
func (c *packageVersionController) GetInstance(ctx *fiber.Ctx) error {
	id := ctx.Query("id")
	packageId := ctx.Query("packageId")
	if id == "" && packageId == "" {
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorParamRequired,
			Msg:  "ID必须提供!",
		})
	}
	pack, err := service.PackageVersionService.Get(&model.PackageVersion{Id: id, PackageId: packageId})
	if err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorInternal,
			Msg:  "服务出现异常",
		})
	}
	return ctx.JSON(&domain.CommonResponse{
		Data: pack,
	})
}

//List GET
func (c *packageVersionController) List(ctx *fiber.Ctx) error {
	condition := new(model.PackageVersion)
	if err := ctx.QueryParser(condition); err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorParamParse,
			Msg:  "参数解析失败!",
		})
	}
	limit, offset, orderBy, err := server.ParsePaginationInfoFromQuery(ctx)
	if err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorParamParse,
			Msg:  "参数解析失败!",
		})
	}

	pi, err := service.PackageVersionService.List(condition, limit, offset, orderBy)
	if err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorInternal,
			Msg:  "服务出现异常",
		})
	}
	return ctx.JSON(&domain.CommonResponse{Data: pi})
}
